/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.speech;

import java.io.File;
import java.util.Calendar;
import javamail.sip.*;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;
import javamail.rtp.rtp;
import javax.media.MediaLocator;
import javax.media.format.AudioFormat;

/**
 *
 * @author sriram
 */
public class speechManager extends Thread{
    // Set the number of maximum messages to be 100
    private static final int MAX_MESSAGES_QUEUED = 100;
    private static final int MAX_MESSAGES_PER_CYCLE = 10;
    private boolean msgDebug = true;
    private boolean debugEnabled = true;
    String callid = null;
    ArrayBlockingQueue msgQ = null;
    rtp rtpObj = null;
    File f = null;
    private MediaLocator playMl = null;
    private String playFile = "play.wav";
    private MediaLocator recordMl = null;
    private String recordFile = "record.wav";
    private String synthesizeFile = "synthesize.wav";
    Object waitForEndOfRecording = new Object();

    public speechManager(String callid, String lHost, int lPort, String rHost, int rPort, AudioFormat[] fmt) {
        msgQ = new ArrayBlockingQueue(MAX_MESSAGES_QUEUED);
        this.callid = callid;
        rtpObj = new rtp(lHost, lPort, rHost, rPort, fmt);
    }

    public void close() {
        // Stop all RTP objects
        rtpObj.stopRtp();
    }

    @Override
    public void run() {
        // Initialize the RTP data for sending and receiving audio

        while(true) {
            try {
                // Sleep for 200 milliseconds before checking
                // for new messages to process
                sleep(200);
                checkForNewMessages();
            } catch(InterruptedException e) {
                checkForNewMessages();
            }
        }
    }
    
    public void checkForNewMessages() {
        speechMessage temp = null;
        for(int i=0; i<MAX_MESSAGES_PER_CYCLE; i++) {
            if((temp = (speechMessage) msgQ.poll()) != null) {
                if(debugEnabled)
                    System.out.println("speechManager::checkForNewMessages-Total Queue size"+msgQ.size());
                processMessage(temp);
            } else {
                break;
            }
        }
    }
    
    public boolean processMessage (speechMessage msg) {
        if(msgDebug) {
            System.out.println("speechManager::processMessage-Incoming Message received");
            System.out.println(msg.method.toName()+":"+msg.body);
        }
        switch(msg.method) {
            case SYNTHESIZE:
                if(msg.containsBody()) {
                    //javamail.main.glblConfig.setMessageText(msg.body);
                    //javamail.main.glblConfig.setMessageReceived(Calendar.getInstance().getTime());
                    // Generate the wav file for voice mail service
                    speechSynthesizer synthesizer = new speechSynthesizer();
                    synthesizer.synthesize(msg.body, synthesizeFile);
                }
                break;
            case RECORD:
                if(msg.containsBody())
                    f = new File(msg.body);
                else
                    f = new File(recordFile);
                String file = null;
                if(f!=null) {
                    file = "file:"+f.getAbsolutePath();
                    recordMl = new MediaLocator(file);
                    rtpObj.startRecording(recordMl);
                }
                //rtpObj.waitForEndOfRecording();
                //rtpObj.stopRecording();
                break;
            case STOPRECORD:
                rtpObj.stopRecording();
                break;
            case PLAY:
                if(msg.containsBody())
                    f = new File(msg.body);
                else
                    f = new File(playFile);
                if(f!=null) {
                    file = "file:"+f.getAbsolutePath();
                    playMl = new MediaLocator(file);
                    rtpObj.startTransmit(playMl);
                    rtpObj.startPlaying();
                }
                break;
            case STOPPLAY:
                rtpObj.stopPlaying();
            case TRANSCRIBE:
                if(msg.containsBody()) {
                    String transcribed = speechTranscriber.transcribe(msg.body);
                }
                break;
            case SKIP:
                if(msg.containsBody()) {
                    try {
                        int time = Integer.parseInt(msg.body);
                        rtpObj.skipRelative(time);
                    } catch (NumberFormatException e) {}
                }
                break;
            case STOP:
                rtpObj.stopRtp();
                break;
            default:
                break;
        }
        return true;
    }

    public boolean queue(speechMessage msg) {
        try {
            if(debugEnabled)
                System.out.println("sipMessageAcceptor::send-Message sucessfully queued");
            return msgQ.add(msg);
        } catch (Exception e) {
            if(debugEnabled)
                System.out.println("sipMessageAcceptor::send-Unable to queue the message: " + e.getMessage());
            return false;
        }

    }
}
